#!/bin/bash
# ----------------------------------------------------------------------
# name:         openserver_auto.sh 
# version:      1.0
# createTime:   2018-03-25
# description:  开服脚本,生成新服数据库
# author:       王文凡
# param:        server_id port_i dbname dbpasswd
# ----------------------------------------------------------------------

# 参数验证
if [ $# != 4 ] ; then 
 echo "USAGE: $0 need targetServerId and codeServerId" 
 exit 1; 
fi 
# 验证源游戏目录
FromServerDir="/server/gameserver"
if [ ! -d $FromServerDir ]; then
  echo "resouce /server/gameserver  dir is not exist" 
 exit 1;
fi

#定义数据库名称
sqlname="reigngamedata_dev_1.sql"
sqlname2="reigngamelog_dev_1.sql"  
dir="/server/script"  
host="127.0.0.1"  
PORT="3306"
user=$3 
passwd=$4  
dbname="reigngamedata_dev_"$1
dbname2="reigngamelog_dev_"$1  


echo 'create databases'

#创建数据库
create_db_sql="create database IF NOT EXISTS ${dbname}"
mysql -h${host} -P${PORT} -u${user} -p${passwd} -e "${create_db_sql}"

create_db_sql2="create database IF NOT EXISTS ${dbname2}"
mysql -h${host} -P${PORT} -u${user} -p${passwd} -e "${create_db_sql2}"
  
#导入sql文件到指定数据库  
mysql -h$host -u$user -p$passwd $dbname < $dir/$sqlname 
mysql -h$host -u$user -p$passwd $dbname2 < $dir/$sqlname2 

#拷贝游戏文件
echo 'copy server beam'
\cp -rf /server/gameserver /server/gameserver_$1

#服务器id
sid=$1
if [[ $sid -le 9 ]];then
	sid="0"$1
fi
curdata=`date "+%Y-%m-%d"`
curtime=`date -d "$curdata 00:00:00" +%s`

#服务器端口
TargetPort=$2
echo 'modify config'$TargetPort

#替换游戏配置文件
cd /server/gameserver_$1/config
sed -i  's/server_id,\([0-9]\)\+/server_id,'$1'/g;s/reigngamedata_dev_\([0-9]\)\+/reigngamedata_dev_'$1'/g;s/reigngamelog_dev_\([0-9]\)\+/reigngamelog_dev_'$1'/g;s/tcp_accept_user_port, \([0-9]\)\+/tcp_accept_user_port, '$TargetPort'/g;s/server_open_timestamp, \([0-9]\)\+/server_open_timestamp, '$curtime'/g' server.config

# cd /server/gameserver_$1/script
# sed -i  's/gs_\([0-9]\)\+/gs_'$1'/g' start_gs.sh
rm /server/gameserver_$1/log/* -rf


sed -i '$a\/server\/script\/db\/databackup.sh '$1 /server/script/db/dbbackup.sh

cd /server/gameserver_$1/config
sed -i  's/serverid_other,\[\([0-9]\|,\)*\]/serverid_other,\[\]/g' server.config

#启动游戏服务
echo 'wait 1 secs start server'$1
sleep 1
cd /server/script
./start_gs.sh $1

echo "server stat======"
ps -ef | grep gs_$1 | grep -v grep | wc -l


echo 'process over'
